package com.manage.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.manage.pojo.Users;
import com.manage.service.UsersService;
import com.manage.utils.FBJSONResult;
import com.manage.utils.MD5Utils;
import com.manage.utils.PagedResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(value = "有关用户操作的接口", tags = {"有关用户操作的接口"})
public class UsersController {

    @Autowired
    private UsersService userService;

    @ApiOperation(value = "用户注册", notes = "用户注册接口")
    @PostMapping("/user/userRegist")
    public FBJSONResult usersRegist(@RequestBody Users user) throws Exception {
        //判断用户id和密码必须不为空
        if (StringUtils.isBlank(user.getUserId()) || StringUtils.isBlank(user.getUserPassword())) {
            return FBJSONResult.errorMsg("用户名和密码不能为空");
        }
        //判断用户ID是否存在
        boolean userIdIsExit = userService.queryUsersIsExit(user.getUserId());
        //保存用户注册信息
        if (!userIdIsExit) {
            user.setUserId(user.getUserId());
            user.setUserName(user.getUserName());
            user.setUserPassword(MD5Utils.getMD5Str(user.getUserPassword()));

            user.setUserCard(user.getUserCard());
            user.setUserBankCard(user.getUserBankCard());
            user.setUserAddress(user.getUserAddress());
            user.setUserPhone(user.getUserPhone());
            user.setUserUsername(user.getUserUsername());
            user.setUserIsBussiness(user.getUserIsBussiness());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            user.setCreateTime(sdf.format(new Date()));
            userService.saveUsers(user);
        } else {
            return FBJSONResult.errorMsg("用户账号已经存在，请换一个再试");
        }
        return FBJSONResult.ok(user);
    }

    @ApiOperation(value = "用户头像上传", notes = "用户头像上传的接口")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "query")
    @PostMapping("/user/userUploadFace")
    public FBJSONResult userUploadFace(String userId, @RequestParam("file") MultipartFile[] files, HttpServletRequest request) throws Exception {
        if(StringUtils.isBlank(userId)) {
            return FBJSONResult.errorMsg("用户id不能为空");
        }
        //文件保存的名密空间
        String fileSpace = "C:/Files/chenrui/bookshop/src/images";
        String hostUrl = "http://127.0.0.1:8081/images";
        //保存到数据库中的相对路径
        String userUploadPathDB = "/avator/" + userId;
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        try {
            if(files != null && files.length > 0) {
                //file的名字
                //file的名字
                String originalFileName = files[0].getOriginalFilename();
                String extName = originalFileName.substring(originalFileName.lastIndexOf("."));
                String fileName = UUID.randomUUID() + extName;
                if(StringUtils.isNoneBlank(fileName)) {
                    //文件上传的最终保存路径
                    String finalFacePath = fileSpace + userUploadPathDB + "/" + fileName;
                    //设置数据库保存的路径
                    userUploadPathDB = hostUrl + userUploadPathDB + "/" + fileName;;
                    File outFile = new File(finalFacePath);
                    if(outFile.getParentFile() != null || outFile.getParentFile().isDirectory()) {
                        //创建父文件夹
                        outFile.getParentFile().mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(outFile);
                    inputStream = files[0].getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                }
            } else {
                return FBJSONResult.errorMsg("上传出错。。。0");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return FBJSONResult.errorMsg("上传出错。。。1");
        } finally {
            if(fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }
        Users user = new Users();
        user.setUserId(userId);
        user.setUserAvator(userUploadPathDB);
        userService.updateUserInfo(user);
        return FBJSONResult.ok(user);
    }

    @ApiOperation(value = "用户登录", notes = "用户登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户账号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userPassword", value = "用户密码", required = true, dataType = "String", paramType = "query")})
    @PostMapping("/user/userLogin")
    public FBJSONResult userLogin(String userId, String userPassword) throws Exception {

        //判断用户账号和密码不能为空
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(userPassword)) {
            return FBJSONResult.errorMsg("用户名和密码不能为空");
        }
        //数据库查找匹配
        Users userResult = userService.queryUserForLogin(userId, MD5Utils.getMD5Str(userPassword));

        if(userResult != null) {
            userResult.setUserPassword("");
            return FBJSONResult.ok(userResult);
        } else {
            return FBJSONResult.errorMsg("用户名或密码不对，请重新输入！");
        }
    }

    @ApiOperation(value = "商家注册更新", notes = "商家注册更新接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "店铺名", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userAddress", value = "店铺地址", required = true, dataType = "String", paramType = "query")})
    @PostMapping("/user/userUpdate")
    public FBJSONResult userUpdate(String userId, String userName, String userAddress) throws Exception {

        if(StringUtils.isBlank(userName) || StringUtils.isBlank(userAddress)) {
            return FBJSONResult.errorMsg("店铺地址和店铺名不能为空");
        }
        //判断用户ID是否存在
        boolean userIdIsExit = userService.queryUsersIsExit(userId);
        if(userIdIsExit) {
            Users user = new Users();
            user.setUserId(userId);
            user.setUserName(userName);
            user.setUserAddress(userAddress);
            user.setUserIsBussiness(1);
            userService.updateUserInfo(user);
            return FBJSONResult.ok(user);
        } else {
            return FBJSONResult.errorMsg("更新失败");
        }
    }

    @ApiOperation(value = "用户密码修改更新", notes = "用户密码修改更新接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userPassword", value = "用户密码", required = true, dataType = "String", paramType = "query")})
    @PostMapping("/user/userUpdateByPassword")
    public FBJSONResult userUpdateByPassword(String userId, String userPassword) throws Exception {

        if(StringUtils.isBlank(userId) || StringUtils.isBlank(userPassword)) {
            return FBJSONResult.errorMsg("用户账号和密码不能为空");
        }
        //判断用户ID是否存在
        boolean userIdIsExit = userService.queryUsersIsExit(userId);
        if(userIdIsExit) {
            userService.updateUserInfoByPassword(userId, userPassword);
            return FBJSONResult.ok("修改成功");
        } else {
            return FBJSONResult.errorMsg("修改失败失败");
        }
    }

    @ApiOperation(value = "用户更新", notes = "用户更新接口")
    @PostMapping("/user/userUpdateAll")
    public FBJSONResult userUpdateAll(@RequestBody Users user) throws Exception {

        //判断用户ID是否存在
        boolean userIdIsExit = userService.queryUsersIsExit(user.getUserId());
        if(userIdIsExit) {
            Users userExample = new Users();
            userExample.setUserId(user.getUserId());
            userExample.setUserName(user.getUserName());
            userExample.setUserAvator(user.getUserAvator());
            userExample.setUserCard(user.getUserCard());
            userExample.setUserBankCard(user.getUserBankCard());
            userExample.setUserAddress(user.getUserAddress());
            userExample.setUserPhone(user.getUserPhone());
            userExample.setUserUsername(user.getUserUsername());
            userService.updateUserInfo(userExample);
            return FBJSONResult.ok(userExample);
        } else {
            return FBJSONResult.errorMsg("更新失败");
        }
    }

    @ApiOperation(value = "用户删除", notes = "用户信息删除接口")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "query")
    @PostMapping("/user/userDelete")
    public FBJSONResult userDelete(String userId) throws Exception {

        if(StringUtils.isBlank(userId)) {
            return FBJSONResult.errorMsg("用户id不能为空");
        }
        //判断用户ID是否存在
        boolean userIdIsExit = userService.queryUsersIsExit(userId);
        //删除用户
        if(userIdIsExit) {
            userService.userDelete(userId);
            boolean userIsDelete = userService.queryUsersIsExit(userId);
            if(userIsDelete) {
                return FBJSONResult.errorMsg("删除失败");
            }
        }
        return FBJSONResult.ok("删除成功");
    }

    @ApiOperation(value = "用户信息查询", notes = "用户信息查询接口")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "query")
    @PostMapping("/user/queryUserInfo")
    public FBJSONResult queryUserInfo(String userId) throws Exception {

        if(StringUtils.isBlank(userId)) {
            return FBJSONResult.errorMsg("用户id不能为空");
        }
        Users userResult = userService.queryUsersInfo(userId);
        userResult.setUserPassword("");
        return FBJSONResult.ok(userResult);
    }

    @ApiOperation(value = "用户列表查询", notes = "用户列表查询接口")
    @PostMapping("/user/queryUsersInfoList")
    public FBJSONResult queryUsersInfoList(Integer page) throws Exception {

        if(page == null) {
            page = 1;
        }
        PagedResult result = userService.getAllUsers(page, 10);
        return FBJSONResult.ok(result);
    }

    @ApiOperation(value = "用户列表查询", notes = "用户列表查询接口")
    @ApiImplicitParam(name = "userIsBussiness", value = "用户身份", required = true, dataType = "Integer", paramType = "query")
    @PostMapping("/user/queryUsersInfoListByUserIsBussiness")
    public FBJSONResult queryUsersInfoListByUserIsBussiness(Integer page,Integer userIsBussiness) throws Exception {

        if(page == null) {
            page = 1;
        }
        PagedResult result = userService.getAllUsersByUserIsBussiness(page, 10, userIsBussiness);
        return FBJSONResult.ok(result);
    }










}
